package com.adinnet.admin.school.service.impl;

import com.adinnet.admin.classCourse.mapper.ClassCourseMapper;
import com.adinnet.admin.classCourse.model.ClassCourse;
import com.adinnet.admin.classs.mapper.ClasssMapper;
import com.adinnet.admin.classs.model.Classs;
import com.adinnet.admin.classs.model.vo.ClassCourseReq;
import com.adinnet.admin.classs.model.vo.ClassCreateReq;
import com.adinnet.admin.common.service.CommonService;
import com.adinnet.admin.organization.mapper.OrganizationMapper;
import com.adinnet.admin.organization.model.Organization;
import com.adinnet.admin.school.model.School;
import com.adinnet.admin.school.mapper.SchoolMapper;
import com.adinnet.admin.school.model.vo.SchoolResp;
import com.adinnet.admin.school.service.SchoolService;
import com.adinnet.admin.system.model.vo.SysUserInfo;
import com.adinnet.common.biz.enums.RoleCode;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResult;
import com.adinnet.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 校区 服务实现类
 * </p>
 *
 * @author liukp
 * @since 2020-12-05
 */
@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements SchoolService {

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private ClasssMapper classsMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private ClassCourseMapper classCourseMapper;

    @Autowired
    private CommonService commonService;

    /**
     * 根据权限查询学校列表
     *
     * 超级管理员查询所有学校
     * 机构查询机构下的所有学校
     * 学校查询本校
     * 老师查询所在学校
     * @param sysUserInfo
     * @return
     */
    @Override
    public List<School> getListByUserRole(SysUserInfo sysUserInfo) {
        QueryWrapper queryWrapper=new QueryWrapper();
        if(RoleCode.ORGANIZATION.getCode().equals(sysUserInfo.getMaxRole())){
            queryWrapper.eq("organization_id",sysUserInfo.getOrganizationId());
        }
        if(RoleCode.SCHOOL.getCode().equals(sysUserInfo.getMaxRole())){
            queryWrapper.eq("id",sysUserInfo.getSchoolId());
        }
        if(RoleCode.CLASSS.getCode().equals(sysUserInfo.getMaxRole())){
            queryWrapper.eq("id",sysUserInfo.getSchoolId());
        }
        queryWrapper.eq("deleted",0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据机构id查询学校列表
     * @param organizationId
     * @return
     */
    @Override
    public List<School> getListByOrganizationId(Integer organizationId,SysUserInfo sysUserInfo) {
        QueryWrapper queryWrapper=new QueryWrapper();
        if(organizationId!=null && organizationId.intValue()>0){
            queryWrapper.eq("organization_id",organizationId);
        }
        if(RoleCode.ORGANIZATION.getCode().equals(sysUserInfo.getMaxRole())){
            queryWrapper.eq("organization_id",sysUserInfo.getOrganizationId());
        }
        if(RoleCode.SCHOOL.getCode().equals(sysUserInfo.getMaxRole())){
            queryWrapper.eq("id",sysUserInfo.getSchoolId());
        }
        if(RoleCode.CLASSS.getCode().equals(sysUserInfo.getMaxRole())){
            queryWrapper.eq("id",sysUserInfo.getSchoolId());
        }
        queryWrapper.eq("deleted",0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * @param keyword:
     * @Description: 查询校区
     * @author zYshuai
     * @Date: 2020/12/11 11:47
     * @return: java.util.List<com.adinnet.admin.school.model.vo.SchoolResp>
     */
    @Override
    public PageResult<SchoolResp> schoolList(String keyword, Integer page, Integer limit) {
        Page<SchoolResp> objectPage = new Page<>(page, limit);
        List<SchoolResp> schoolRespList =schoolMapper.schoolList(objectPage,keyword);
        return new PageResult<>(schoolRespList, objectPage.getTotal());
    }

    /**
     * @Description: 删除校区
     * @author zYshuai
     * @Date: 2020/12/11 11:49
     * @param schoolId:校区id
     * @return: null
     */

    @Override
    public JsonResult delete(Integer schoolId) {
        //判断机构下 校区数和班级数是否为0
        School school = schoolMapper.selectById(schoolId);
        if (null == school) {
            return JsonResult.error("查询校区失败");
        }
        List<Classs> classses = classsMapper.selectList(new QueryWrapper<Classs>().eq("school_id", schoolId).eq("deleted", 0));
        if (CollectionUtils.isNotEmpty(classses)) {
            return JsonResult.error("校区内有" + classses.size() + "个班级，移除班级后才可删除校区。");
        }
        school.setDeleted(true);
        schoolMapper.updateById(school);
        return JsonResult.ok("删除成功");
    }

    @Override
    @Transactional
    public boolean addOrUpdate(ClassCreateReq classCreateReq, SysUserInfo sysUserInfo, HttpServletRequest request) {
        if (null == classCreateReq.getId()) {
            //新增
            Classs classs=new Classs();
            classs.setClassName(classCreateReq.getClassName());
            classs.setSchoolId(classCreateReq.getSchoolId());
            classs.setSysUserId(classCreateReq.getSysUserId());
            classs.setTeacherUserId(classCreateReq.getTeacherUserId());
            classsMapper.insert(classs);
            //todo  判断-超级管理员创建则直接审核通过，机构或其他创建则需要审核
            if (CollectionUtils.isNotEmpty(classCreateReq.getClassCourseReqs())) {
                if (RoleCode.ADMIN.getCode().equals(sysUserInfo.getMaxRole())) {
                    for (ClassCourseReq classCourseReq : classCreateReq.getClassCourseReqs()) {
                        ClassCourse classCourse = new ClassCourse();
                        classCourse.setClassId(classs.getId());
                        classCourse.setStatus(1);
                        classCourse.setAuditStatus(3);
                        classCourse.setCourseId(classCourseReq.getCourseId());
                        classCourse.setUnitName(classCourseReq.getUnitName());
                        classCourseMapper.insert(classCourse);
                    }
                }else {
                    for (ClassCourseReq classCourseReq : classCreateReq.getClassCourseReqs()) {
                        ClassCourse classCourse = new ClassCourse();
                        classCourse.setClassId(classs.getId());
                        classCourse.setStatus(0);
                        classCourse.setAuditStatus(0);
                        classCourse.setCourseId(classCourseReq.getCourseId());
                        classCourse.setUnitName(classCourseReq.getUnitName());
                        classCourseMapper.insert(classCourse);
                    }
                }
            }
            commonService.saveOperation(request,"新增班级，班级名称："+classCreateReq.getClassName());
            return true;
        } else {
            //修改
            Classs classs = classsMapper.selectById(classCreateReq.getId());
            if(null==classs){
                throw new BizException("班级不存在!");
            }
            classs.setClassName(classCreateReq.getClassName());
            classs.setSchoolId(classCreateReq.getSchoolId());
            classs.setSysUserId(classCreateReq.getSysUserId());
            classs.setTeacherUserId(classCreateReq.getTeacherUserId());
            classs.setUpdatedDate(new Date());
            classsMapper.updateById(classs);
            QueryWrapper<ClassCourse> wrapper = new QueryWrapper<>();
            wrapper.eq("class_id", classCreateReq.getId());
            ClassCourse course = new ClassCourse();
            if (CollectionUtils.isNotEmpty(classCreateReq.getClassCourseReqs())) {
                //2021-06-10 新增和编辑班级时不修改班级课程，只有在课程状态里才需要要修改
                course.setDeleted(true);
                classCourseMapper.update(course, wrapper);
                if (RoleCode.ADMIN.getCode().equals(sysUserInfo.getMaxRole())) {
                    for (ClassCourseReq classCourseReq : classCreateReq.getClassCourseReqs()) {
                        ClassCourse classCourse = new ClassCourse();
                        classCourse.setClassId(classs.getId());
                        classCourse.setStatus(1);
                        classCourse.setAuditStatus(3);
                        classCourse.setCourseId(classCourseReq.getCourseId());
                        classCourse.setUnitName(classCourseReq.getUnitName());
                        classCourseMapper.insert(classCourse);
                    }
                }else {
                    for (ClassCourseReq classCourseReq : classCreateReq.getClassCourseReqs()) {
                        ClassCourse classCourse = new ClassCourse();
                        classCourse.setClassId(classs.getId());
                        classCourse.setStatus(0);
                        classCourse.setAuditStatus(0);
                        classCourse.setCourseId(classCourseReq.getCourseId());
                        classCourse.setUnitName(classCourseReq.getUnitName());
                        classCourseMapper.insert(classCourse);
                    }
                }
            }
            commonService.saveOperation(request,"修改班级，班级ID："+classCreateReq.getId());
            return true;
        }
    }
}
